﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VDS.RDF;
using VDS.RDF.Storage;
using System.Configuration;
using System.Data;

namespace LCMS_MVC.Models
{
    public class QueryModel
    {
        private string _graphUri;
        private VirtuosoManager _manager;
        public Graph _outputGraph;
        public string _outputText;

        private const String VirtuosoQuadStoreDB = "DB";
        string username = ConfigurationManager.AppSettings["VirtuosoUsername"];
        string password = ConfigurationManager.AppSettings["VirtuosoPassword"];
        string server = ConfigurationManager.AppSettings["VirtuosoServer"];
        int port = Int32.Parse(ConfigurationManager.AppSettings["VirtuosoPort"]);


            
        public QueryModel(string u)
        {
            this._manager = new VirtuosoManager(server, port, VirtuosoQuadStoreDB, username, password);
            this._graphUri = u;
            this._outputText = "Nothing to say yet";
            this._outputGraph = this.ViewGraph(u);

        }

        public Graph ViewGraph(string u)
        {
            this._graphUri = u;
            this._outputText = "Browsing Graph '" + u.ToString() + "'";
            Graph g = new Graph();
            try
            {
                //Load the Graph from Virtuoso
                this._manager.LoadGraph(g, u);
                if (g.IsEmpty)
                {
                    //If we get an Empty Graph then we want to try DESCRIBing the resource instead
                    Object result = this._manager.Query("DESCRIBE <" + u.ToString().Replace(">", "\\>") + ">");
                    if (result is Graph)
                    {
                        g = (Graph)result;
                        this._outputText = "Browsing DESCRIBE of '" + u.ToString() + "'";
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to load the Graph '" + u.ToString() + "'\n\n" + ex.Message);
            }

            return g;        
        }

    }
}